// 如果你想让这个组件成为客户端组件：  
'use client';

import { useEffect, useRef, useState } from "react";
import Game from "./Game";
import {debounce, throttle} from 'lodash';

export default function GamePad() {
    const [state, _setState] = useState({
        button: ''
    });
    const setState = (params: { [key: string]: any }) => {
        _setState((_state) => ({ ..._state, ...params }));
    };
    const { button} = state;
    const game: { current: Game } = useRef() as any
    const init = () => {
        game.current = new Game(debounce((e:number)=>{
            console.log(Date.now(), e)
            setState({
                button: e
            })
        }, 50));
    }
    useEffect(() => {
        init();
        window.addEventListener("gamepadconnected", game.current.connect);
        window.addEventListener("gamepaddisconnected", game.current.disconnect);
        return () => {
            window.removeEventListener("gamepadconnected", game.current.connect);
            window.removeEventListener("gamepaddisconnected", game.current.disconnect);
            game.current =null as any;
        }
    }, [])
    return <main className="min-h-screen">
        {button}
    </main>
}